package com.clouds.wms.dao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Repository;

import com.clouds.wms.bean.Cmsmg;
import com.clouds.wms.exception.DatabaseException;

@Repository("cmsmgDao")
public class CmsmgDaoImpl implements CmsmgDao {

	private Log log = LogFactory.getLog(getClass());
	
	@Resource(name="namedParameterJdbcTemplate")
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	
	@Override
	public int[] saveCmsmgs(List<Cmsmg> cmsmgList) throws DatabaseException {
		try {
			SqlParameterSource[] batchArgs = SqlParameterSourceUtils.createBatch(cmsmgList.toArray());
			String sql = "INSERT INTO cmsmg (mgab, mgac) VALUES (:mgab, :mgac)";
			return namedParameterJdbcTemplate.batchUpdate(sql, batchArgs);
		} catch(Exception e) {
			log.error(e.getMessage(), e);
			throw new DatabaseException(e.getMessage());
		}
	}
	
	@Override
	public List<Cmsmg> getCmsmgListByMbaa(String mbaa) throws DatabaseException {
		String sql = "SELECT * FROM cmsmg WHERE mgab=?";
		try {
			return namedParameterJdbcTemplate.getJdbcOperations().query(sql, new Object[]{mbaa}, new BeanPropertyRowMapper<Cmsmg>(Cmsmg.class));
		} catch (Exception e) {
			log.error("exception :", e);
			throw new DatabaseException(e.getMessage());
		}
	}

	@Override
	public int deleteCmsmgListByMbaa(String mbaa) throws DatabaseException {
		String sql = "DELETE FROM cmsmg WHERE mgab=?";
		try {
			return namedParameterJdbcTemplate.getJdbcOperations().update(sql, new Object[]{mbaa});
		} catch (Exception e) {
			log.error("exception :", e);
			throw new DatabaseException(e.getMessage());
		}
	}
	
}
